<template>
  <div class="settings">
    <van-nav-bar safe-area-inset-top placeholder :title="$t('Load2Setting')" left-arrow fixed @click-left="onClickLeft" />
    <div class="marginTop15">
      <van-pull-refresh v-model="isLoading" :pulling-text="$t('PullingText')" :loosing-text="$t('PullingText')" :success-text="$t('refreshSuccee')" @refresh="onRefresh">
        <van-cell-group>
          <van-cell :title="$t('Status')" :value="revealDatas.relay2Status==1?$t('Open'):$t('Off')" />
          <van-cell :title="$t('Power')" :value="revealDatas.relay2Power | numFilter(2,'W')" />
          <van-cell :title="$t('Energy')" :value="revealDatas.relay2Energy | numFilter(2,'kWh')" />
          <van-cell :title="$t('Match')">
            <template #right-icon>
              <van-button size="small" :type="types" round class="setbtn" @click="setMatch">{{$t('Save')}}</van-button>
            </template>
          </van-cell>
          <resetINVEnergyVue :setName="$t('ResetLoadEnergy')" :valName="'ResetConsumValue'" :subOption="'relay2Consum'"></resetINVEnergyVue>
        </van-cell-group>
        <van-collapse v-model="activeNames" v-if="isMatch">
          <van-collapse-item :title="$t('Load2Setting')" name="1">
          <van-form @submit="Relay1SettingSubmit">
            <van-field :value="TriggerMode" :label="$t('TriggerMode')" readonly clickable name="picker" input-align="right" @click="showTrigger = true" />
            <van-popup v-model="showTrigger" round position="bottom">
              <van-picker show-toolbar :columns="triggerArr" 
                @cancel="showTrigger = false" 
                @confirm="triggerModeConfirm"
                :confirm-button-text="$t('OK')"
                :cancel-button-text="$t('Cancel')"  
              />
            </van-popup>
            <van-field :value="ManualMode" :label="$t('ManualControl')" readonly clickable name="picker" input-align="right" @click="showManual = true" v-if="TriggerModeCode==1" />
            <van-popup v-model="showManual" round position="bottom">
              <van-picker show-toolbar :columns="manualArr" 
                @cancel="showManual = false" 
                @confirm="manualConfirm" 
                :confirm-button-text="$t('OK')"
                :cancel-button-text="$t('Cancel')"
              />
            </van-popup>
            <van-field v-if="TriggerModeCode==2||TriggerModeCode==3"
              v-model="TrigPowerValue" 
              :label="$t('TrigPower')"
              type="digit" 
              show-error 
              name="validator" 
              input-align="right" 
              error-message-align="right" 
              clearable 
              :rules="[{ validator:fixed1,message: `${$t('Range')}：50-5000` }]" 
            />
            <van-field v-if="TriggerModeCode==2||TriggerModeCode==3"
              v-model="TrigTimeSetValue" 
              :label="$t('TriggerMinutes')" 
              type="digit" 
              show-error 
              name="validator" 
              input-align="right" 
              error-message-align="right" 
              clearable 
              :rules="[{ validator:fixed2,message: `${$t('Range')}：1-10` }]" 
            />
            <van-field v-if="TriggerModeCode==2||TriggerModeCode==3"
              v-model="CloseTimeSetValue" 
              :label="$t('CloseTimeSet')" 
              type="digit" 
              show-error 
              name="validator" 
              input-align="right" 
              error-message-align="right" 
              clearable 
              :rules="[{ validator:fixedTwo1,message: `${$t('Range')}：0.1-24.0` }]" 
            />
            <van-cell :title="$t('StartTime')" :value="startTimeValue" @click="showStartTime=true" v-if="TriggerModeCode==4" />
            <van-popup v-model="showStartTime" round position="bottom">
              <van-datetime-picker v-model="currentStartTime" type="time" 
                @cancel="showStartTime = false" 
                @confirm="startTimeConfirm" 
                :confirm-button-text="$t('OK')"
                :cancel-button-text="$t('Cancel')"
              />
            </van-popup>
            <van-cell :title="$t('EndTime')" :value="endTimeValue" @click="showEndTime=true" v-if="TriggerModeCode==4" />
            <van-popup v-model="showEndTime" round position="bottom">
              <van-datetime-picker v-model="currentEndTime" type="time" 
                @cancel="showEndTime = false" 
                @confirm="endTimeConfirm" 
                :confirm-button-text="$t('OK')"
                :cancel-button-text="$t('Cancel')" 
              />
            </van-popup>
            <div class="factorBtnBox">
              <van-button block round>{{$t('Save')}}</van-button>
            </div>
          </van-form>
        </van-collapse-item>
        </van-collapse>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script>
import resetINVEnergyVue from '../../../components/ResetINVEnergy/ResetINVEnergy'
export default {
  components:{
    resetINVEnergyVue
  },
  data(){
    return {
      transportType:localStorage.getItem('transportType'),
      isLoading:false,
      activeNames:[],
      revealDatas:'',
      types:'primary',
      isMatch:false,
      MatchValue:'',
      showTrigger:false,
      triggerArr:[this.$t('Disabled'),this.$t('Manual'),this.$t('Once'),this.$t('Cycle'),this.$t('Force')],
      TriggerMode:'',
      TriggerModeCode:'',
      showManual:false,
      manualArr:[this.$t('Off'),this.$t('Open')],
      ManualMode:'',
      ManualModeCode:'',
      TrigPowerValue:'',
      TrigTimeSetValue:'',
      CloseTimeSetValue:'',
      showStartTime:false,
      startTimeValue:'',
      currentStartTime:'',
      showEndTime:false,
      endTimeValue:'',
      currentEndTime:''
    }
  },
  methods: {
    onClickLeft(){
      this.$router.push({path:'/rfcontrol'});
    },
    //获取展示数据
    async setRfRevealData(){
      let data = await this.SETAPI.setRfRevealData(localStorage.getItem('domain'),{'tokenId':localStorage.getItem('tokenId'),'sn':localStorage.getItem('sn'),'wifiSn':localStorage.getItem('wifiSN')});
      this.revealDatas=data.result||[];
      //判断匹配状态
      if(this.revealDatas.relay2answer==0){
        this.types='primary';
        this.isMatch=true;
      }else if(this.revealDatas.relay2answer==9||this.revealDatas.relay2answer==10){
        this.types='warning';
        this.isMatch=false;
      }else{
        this.types='danger';
        this.isMatch=false;
      }
    },
    triggerModeConfirm(value,i){
      this.showTrigger=false;
      this.TriggerMode=value;
      this.TriggerModeCode=i;
    },
    manualConfirm(value,i){
      this.showManual=false;
      this.ManualMode=value;
      this.ManualModeCode=i;
    },
    startTimeConfirm(val){
      this.showStartTime=false;
      this.startTimeValue=val;
    },
    endTimeConfirm(val){
      this.showEndTime=false;
      this.endTimeValue=val;
    },
    //设置Match
    async setMatch(){
      //处理数据
      let params={
        'optType':'relay2Match',
        'sn':localStorage.getItem('wifiSN'),
        'tokenId':localStorage.getItem('tokenId'),
        'relay2MatchValue':1
      };
      this.comm.loadingShow();
      let data = await this.SETAPI.setInvMachine(localStorage.getItem('domain'), params);
      if (data.success) {
        this.comm.toastSuccess();
        /*判断用户的选择*/
        this.isMatch=true;
        this.types='primary';
      } else if (data.result === "tokenId不合法!") {
        this.comm.loginAgain();
      } else {
        this.comm.toastFail();
      }
    },
    //Relay2参数设置
    Relay1SettingSubmit(){
      let StartTimeArr=this.startTimeValue.split(':');
      let EndTimeArr=this.endTimeValue.split(':');
      let formData={
        'TrigModeValue':this.TriggerModeCode,
        'ManualControlValue':this.ManualModeCode,
        'TrigPowerValue':this.TrigPowerValue,
        'TrigTimeSetValue':this.TrigTimeSetValue,
        'CloseTimeSetValue':this.comm.mulFunction(this.CloseTimeSetValue,10),
        'StartTime1_H':StartTimeArr[0],
        'StartTime1_M':StartTimeArr[1],
        'EndTime1_H':EndTimeArr[0],
        'EndTime1_M':EndTimeArr[1]
      };
      this.comm.setData('relay2Setting',formData);
    },
    fixed1(val){
      let vaild;
      if(val>=50&&val<=5000){
        vaild=true;
      }else{
        vaild=false;
      }
      return vaild;
    },
    fixed2(val){
      let vaild;
      if(val>=1&&val<=10){
        vaild=true;
      }else{
        vaild=false;
      }
      return vaild;
    },
    fixedTwo1(val){
      return this.comm.fixedTwo(val,0.1,24);
    },
    //获取设置数据
    async getData(){
      this.comm.loadingShow();
      let datas = await this.SETAPI.setGetData(localStorage.getItem('domain'),{'tokenId':localStorage.getItem('tokenId'),'sn':localStorage.getItem('wifiSN')});
      if(datas.result!=null&&datas.result!="tokenId不合法!"){
        let dataArr=JSON.parse(datas.result);
        this.TriggerModeCode=dataArr[117];
        this.TriggerMode=this.triggerArr[this.TriggerModeCode];
        this.ManualModeCode=dataArr[120];
        this.ManualMode=this.manualArr[this.ManualModeCode];
        this.TrigPowerValue=dataArr[115];

        let TrigTimeSetHandle= dataArr[116];
        let TrigTimeSetHandle1=parseInt(TrigTimeSetHandle/256);
        let TrigTimeSetHandle2=TrigTimeSetHandle%256;
        this.TrigTimeSetValue=TrigTimeSetHandle2;
        this.CloseTimeSetValue=TrigTimeSetHandle1/10;

        let startTime1Handle= dataArr[118];
        let startTime1Handle1= parseInt(startTime1Handle/256);
        let startTime1Handle2=startTime1Handle%256;
        startTime1Handle1=parseInt(startTime1Handle1)>=10?startTime1Handle1:"0"+startTime1Handle1;
        startTime1Handle2=parseInt(startTime1Handle2)>=10?startTime1Handle2:"0"+startTime1Handle2;
        this.startTimeValue=`${startTime1Handle1}:${startTime1Handle2}`;

        let endTime1Handle= dataArr[119];
        let endTime1Handle1= parseInt(endTime1Handle/256);
        let endTime1Handle2=endTime1Handle%256;
        endTime1Handle1=parseInt(endTime1Handle1)>=10?endTime1Handle1:"0"+endTime1Handle1;
        endTime1Handle2=parseInt(endTime1Handle2)>=10?endTime1Handle2:"0"+endTime1Handle2;
        this.endTimeValue=`${endTime1Handle1}:${endTime1Handle2}`;
      }else{
        this.comm.tipsShow('InvNoResponse');
      }
    },
    onRefresh(){
      this.isLoading = false;
      this.setRfRevealData();
      this.getData();
    }
  },
  mounted(){
    this.setRfRevealData();
    this.getData();
  }
}
</script>

<style scoped lang="less">

</style>
